
package cookie.correct;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.e885.log.E885Logger;

/**
 * url: http://127.0.0.1:8080/JSP/cookie/correctGet<br>
 * 取得 Cookie 的資訊，但是目前只能取得 cookie name and value, 其它的值無法取得。
 * 
 * @author Grady.Kao
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2000-2008
 */

public class CookieCorrectGetter extends HttpServlet
{
	private static final long serialVersionUID = -5989926388798653948L;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
	{
		E885Logger.testLog.debug( "execute CookieCorrectGetter.service() to get Cookie" );

		response.setContentType( "text/html;charset=UTF-8" );
		PrintWriter writer = response.getWriter();

		Cookie[] cookies = request.getCookies();
		if( cookies == null )
			cookies = new Cookie[ 0 ];

		writer.println( "為了安全理由，Cookie 只可以被特定的伺服器所讀取<br>" );
		writer.println( "PS: 在這裏特定的伺服器是指當初設定 cookie 的伺服器或位在相同網或的其它伺服器<br>" );
		writer.println( "<br>" );
		writer.println( "以下會列出所有的 Cookies by 特定的伺服器<br>" );

		for( int i = 0; i < cookies.length; i++ )
		{
			String value = URLDecoder.decode( cookies[ i ].getValue(), "UTF-8" ); // 因為在 add cookie 有做 encode 的動作

			writer.println( "=========================================================<br>" );
			writer.println( "name:" + cookies[ i ].getName() + "<br>" ); // 傳回 cookie 的名稱
			writer.println( "value:" + value + "<br>" ); // 傳回 cookie 的對應值
			writer.println( "domain:" + cookies[ i ].getDomain() + "<br>" ); // 傳回可以存取 Cookie 的伺服器或是網域
			writer.println( "Path:" + cookies[ i ].getPath() + "<br>" ); // 傳回可以存取 Cookie 的 URL 路徑
			writer.println( "MaxAge:" + cookies[ i ].getMaxAge() + "<br>" );// 傳回 Cookie 到期之前的剩餘時間
			writer.println( "secure:" + cookies[ i ].getSecure() + "<br>" ); // 傳回 Cookie 是否僅限 HTTPS 要求才能存取
			writer.println( "version:" + cookies[ i ].getVersion() + "<br>" );
			writer.println( "comment:" + cookies[ i ].getComment() + "<br>" );
		}

		writer.close();
	}
}
